import 'package:flutter/material.dart';
import '../models/category.dart';
import '../models/transaction.dart';
import '../services/database_service.dart';

class CategoryManagePage extends StatefulWidget {
  const CategoryManagePage({super.key});

  @override
  State<CategoryManagePage> createState() => _CategoryManagePageState();
}

class _CategoryManagePageState extends State<CategoryManagePage> {
  late Future<List<Category>> _categoriesFuture;
  TransactionType _selectedType = TransactionType.expense;

  @override
  void initState() {
    super.initState();
    _loadCategories();
  }

  void _loadCategories() {
    _categoriesFuture = DatabaseService.instance.getCategoriesByType(_selectedType);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('分类管理'),
      ),
      body: Column(
        children: [
          _buildTypeSelector(),
          Expanded(
            child: FutureBuilder<List<Category>>(
              future: _categoriesFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (snapshot.hasError) {
                  return Center(child: Text('错误: ${snapshot.error}'));
                }

                final categories = snapshot.data ?? [];

                return ReorderableListView.builder(
                  padding: const EdgeInsets.all(8),
                  itemCount: categories.length,
                  onReorder: (oldIndex, newIndex) {
                    setState(() {
                      if (oldIndex < newIndex) {
                        newIndex -= 1;
                      }
                      final item = categories.removeAt(oldIndex);
                      categories.insert(newIndex, item);
                      DatabaseService.instance.updateCategoriesOrder(categories);
                    });
                  },
                  itemBuilder: (context, index) {
                    final category = categories[index];
                    return Card(
                      key: ValueKey(category.id),
                      child: ListTile(
                        leading: Icon(IconData(
                          int.parse('0x${category.icon}'),
                          fontFamily: 'MaterialIcons',
                        )),
                        title: Text(category.name),
                        trailing: category.isDefault
                            ? const Chip(
                                label: Text('默认'),
                                backgroundColor: Colors.grey,
                              )
                            : IconButton(
                                icon: const Icon(Icons.delete),
                                onPressed: () => _deleteCategory(category),
                              ),
                        onTap: () => _editCategory(category),
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addCategory,
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildTypeSelector() {
    return SegmentedButton<TransactionType>(
      segments: const [
        ButtonSegment(
          value: TransactionType.expense,
          label: Text('支出'),
          icon: Icon(Icons.remove_circle_outline),
        ),
        ButtonSegment(
          value: TransactionType.income,
          label: Text('收入'),
          icon: Icon(Icons.add_circle_outline),
        ),
      ],
      selected: {_selectedType},
      onSelectionChanged: (Set<TransactionType> newSelection) {
        setState(() {
          _selectedType = newSelection.first;
          _loadCategories();
        });
      },
    );
  }

  Future<void> _addCategory() async {
    final result = await showDialog<CategoryFormResult>(
      context: context,
      builder: (context) => CategoryFormDialog(
        type: _selectedType,
      ),
    );

    if (result != null) {
      final category = Category(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        name: result.name,
        icon: result.icon,
        type: _selectedType,
        sortOrder: 999, // 临时排序号
      );

      try {
        await DatabaseService.instance.insertCategory(category);
        setState(() {
          _loadCategories();
        });
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('添加失败: $e')),
          );
        }
      }
    }
  }

  Future<void> _editCategory(Category category) async {
    if (category.isDefault) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('默认分类不能编辑')),
      );
      return;
    }

    final result = await showDialog<CategoryFormResult>(
      context: context,
      builder: (context) => CategoryFormDialog(
        type: category.type,
        initialName: category.name,
        initialIcon: category.icon,
      ),
    );

    if (result != null) {
      final updatedCategory = category.copyWith(
        name: result.name,
        icon: result.icon,
      );

      try {
        await DatabaseService.instance.updateCategory(updatedCategory);
        setState(() {
          _loadCategories();
        });
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('更新失败: $e')),
          );
        }
      }
    }
  }

  Future<void> _deleteCategory(Category category) async {
    if (category.isDefault) return;

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个分类吗？相关的交易记录将保持不变。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text(
              '删除',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        await DatabaseService.instance.deleteCategory(category.id);
        setState(() {
          _loadCategories();
        });
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除失败: $e')),
          );
        }
      }
    }
  }
}

class CategoryFormDialog extends StatefulWidget {
  final TransactionType type;
  final String? initialName;
  final String? initialIcon;

  const CategoryFormDialog({
    super.key,
    required this.type,
    this.initialName,
    this.initialIcon,
  });

  @override
  State<CategoryFormDialog> createState() => _CategoryFormDialogState();
}

class _CategoryFormDialogState extends State<CategoryFormDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _nameController;
  String _selectedIcon = 'label';

  final _icons = [
    'label',
    'shopping_bag',
    'restaurant',
    'directions_bus',
    'shopping_cart',
    'home',
    'local_hospital',
    'school',
    'sports_basketball',
    'movie',
    'account_balance_wallet',
    'card_giftcard',
    'attach_money',
    'savings',
  ];

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.initialName);
    if (widget.initialIcon != null) {
      _selectedIcon = widget.initialIcon!;
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.initialName == null ? '添加分类' : '编辑分类'),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextFormField(
              controller: _nameController,
              decoration: const InputDecoration(
                labelText: '分类名称',
                border: OutlineInputBorder(),
              ),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入分类名称';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            const Text('选择图标'),
            const SizedBox(height: 8),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: _icons.map((iconName) {
                return InkWell(
                  onTap: () {
                    setState(() {
                      _selectedIcon = iconName;
                    });
                  },
                  child: Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: _selectedIcon == iconName
                          ? Theme.of(context).primaryColor.withOpacity(0.1)
                          : null,
                      border: Border.all(
                        color: _selectedIcon == iconName
                            ? Theme.of(context).primaryColor
                            : Colors.grey,
                      ),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Icon(IconData(
                      int.parse('0x${iconName}'),
                      fontFamily: 'MaterialIcons',
                    )),
                  ),
                );
              }).toList(),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              Navigator.pop(
                context,
                CategoryFormResult(
                  name: _nameController.text,
                  icon: _selectedIcon,
                ),
              );
            }
          },
          child: const Text('确定'),
        ),
      ],
    );
  }
}

class CategoryFormResult {
  final String name;
  final String icon;

  CategoryFormResult({
    required this.name,
    required this.icon,
  });
} 